<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- ===== 核心搜索条件（常用） ===== -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Name_FormItem" prop="Name">
							<template #label>
								<WtmLabelTooltip label="属性名称" tooltip="物料属性的名称，如颜色、尺寸等" />
							</template>
							<el-input v-model="searchData.Name" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialName_FormItem" prop="MaterialName">
							<template #label>
								<WtmLabelTooltip label="物料名称" tooltip="物料名称" />
							</template>
							<el-input v-model="searchData.MaterialName" clearable placeholder="请输入物料名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialCode_FormItem" prop="MaterialCode">
							<template #label>
								<WtmLabelTooltip label="物料编码" tooltip="物料编码" />
							</template>
							<el-input v-model="searchData.MaterialCode" clearable placeholder="请输入物料编码"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="IsKeyAttribute_FormItem" prop="IsKeyAttribute">
							<template #label>
								<WtmLabelTooltip label="是否关键属性" tooltip="关键属性会生成SKU编码，非关键属性仅用于采购和领用等辅助识别" />
							</template>
							<el-select v-model="searchData.IsKeyAttribute" clearable>
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- ===== 高级搜索条件（可展开） ===== -->
					<template v-if="showAdvanced">
						<!-- 如需添加更多搜索条件，可在此处扩展 -->
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-if="entityId"
				v-auth="'/api/SysMaterialAttribute/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysMaterialAttribute/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysMaterialAttribute/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysMaterialAttribute/SysMaterialAttributeExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
			<!-- AI生成采购属性和采购提示词打开按钮 只有在物料由ID的时候展示 -->
			<template v-if="entityId">
				<WtmButton
					v-auth="'/api/SysMaterialAttribute/AiGenerateNonKeyAttributes'"
					icon="fa fa-tasks"
					type="primary"
					:button-text="aiLoading ? '生成中…' : 'AI生成采购属性'"
					:disabled="aiLoading"
					@click="OnAiGenerateNonKeyAttributesClick()"
				/>
				<WtmButton
					v-auth="'/api/SysMaterialAttribute/AiGeneratePurchaseAttributePrompt'"
					icon="fa fa-tasks"
					type="primary"
					button-text="采购属性提示词"
					@click="openPurchaseAttributePrompt()"
				/>
			</template>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysMaterialAttribute/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysMaterialAttribute/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysMaterialAttribute/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="物料属性;true;HengTong.Areas.SupplyChain.Controllers;SysMaterialAttribute">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed, watch } from 'vue';
import { SysMaterialAttributeApi as api } from '/@/views/supplychain/sysmaterialattribute/api';
import { ISysMaterialAttributeView, ISysMaterialAttributeQuery } from '/@/views/supplychain/sysmaterialattribute/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));
const PurchaseAttributePromptDialog = defineAsyncComponent(() => import('../../_admin/sysprompt/edit.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysMaterialAttributeQuery;
		/** 主表ID */
		entityId?: string | null;
		/** 非关键属性提示词ID（用于打开提示词编辑对话框） */
		promptId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
		promptId: null,
	}
);

const stateData = reactive({
	AllSysMaterials: [] as ISysSelectType[],
});

const aiLoading = ref(false);

const searchData = ref<ISysMaterialAttributeQuery>({
	Name: null,
	IsKeyAttribute: null,
	MaterialId: null,
	MaterialName: null,
	MaterialCode: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）按优先级排序
	header: [
		{ title: '属性名称', key: 'Name', type: 'text', isCheck: true },
		{ title: '物料', key: 'MaterialName', type: 'text', isCheck: true },
		{ title: '是否关键属性', key: 'IsKeyAttribute', type: 'switch', isCheck: true },
		{ title: '属性值列表', key: 'ValuesName', type: 'text', isCheck: true },
		{ title: '排序', key: 'Order', type: 'text', isCheck: true },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	// 如果有 entityId，传递给新增页面
	const data = props.entityId ? { MaterialId: props.entityId } : null;
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, data, getTableData);
};

const OnEditRowClick = (row: ISysMaterialAttributeView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysMaterialAttributeView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};
//打开采购属性提示词
const openPurchaseAttributePrompt = () => {
	if (!props.promptId) {
		ElMessage.warning('没有可编辑的提示词');
		return;
	}
	other.openDialog('采购属性提示词', PurchaseAttributePromptDialog, { ID: props.promptId }, getTableData);
};

// 删除
const onDelete = (row: ISysMaterialAttributeView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysMaterialAttributeView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};
//AI生成采购属性
const OnAiGenerateNonKeyAttributesClick = () => {
	if (aiLoading.value) return;
	const MaterialId = props.entityId || '';
	aiLoading.value = true;
	api()
		.aiGenerateNonKeyAttributes(MaterialId)
		.then(() => {
			ElMessage.success('生成完成');
			getTableData();
		})
		.catch((err) => {
			other.setFormError(ci, err);
		})
		.finally(() => {
			aiLoading.value = false;
		});
};
// 页面加载时
onMounted(() => {
	loading.value = true;

	// 如果有 entityId，设置到搜索条件中
	if (props.entityId) {
		searchData.value.MaterialId = props.entityId;
	}

	const promises: Promise<any>[] = [getTableData()];

	// 只有在显示搜索条件时才加载下拉列表数据
	if (props.searchBar) {
		promises.push(other.getSelectList('/api/SysMaterialAttribute/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x)));
	}

	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
